package tc.maas.bulkfilerenamer.domain.dataobjects;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import tc.maas.bulkfilerenamer.domain.filemanagement.interfaces.Containable;
import tc.maas.bulkfilerenamer.domain.filemanagement.interfaces.Container;
import tc.maas.bulkfilerenamer.utils.enumerators.Delimiters;
import tc.maas.bulkfilerenamer.utils.exceptions.NamingFormatException;
import tc.maas.bulkfilerenamer.utils.texts.ErrorMessages;

public class Directory extends AbstractRenamable implements Container {

    private Map<String, Containable> containables = new HashMap<String, Containable>();
    private DefaultNameFormat defaultNameFormat;

    private Directory() {
    }

    public Directory(final java.io.File file) {
        super();
        if (!file.isDirectory()) {
            throw new IllegalArgumentException("The provided path is not a folder");
        }
        absolutePath = file.getAbsolutePath();
        delimiters = new ArrayList<Delimiters>();
        try {
            name = determineName();
            updateDelimiters();
        } catch (NamingFormatException ex) {
            Logger.getLogger(Directory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public List<Containable> getContainables() {
        return Arrays.asList(containables.values().toArray(new Containable[0]));
    }

    @Override
    public Containable getContainableByName(final String name) {
        return containables.get(name);
    }

    @Override
    public void addAllContainables(final List<Containable> containables) {
        for (Containable containable : containables) {
            addContainable(containable);
        }
    }

    @Override
    public void addContainable(final Containable containable) {
        containables.put(containable.getCurrentName(), containable);
    }

    private String determineName() throws NamingFormatException {
        if (this.defaultNameFormat == null) {
            throw new NamingFormatException(ErrorMessages.NO_NAMING_CONVENTION_FOUND_ERROR.getMessage());
        }
        return defaultNameFormat.getBaseName();
    }

    @Override
    public DefaultNameFormat getDefaultNameFormat() {
        return defaultNameFormat;
    }

    @Override
    public void setDefaultNameFormat(final DefaultNameFormat defaultNameFormat) {
        this.defaultNameFormat = defaultNameFormat;
    }

    @Override
    public void update() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setNewPath() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
